package insert;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class insert_dipendente extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String oracleUser = "azienda";
    private String oraclePwd  = "azienda";
    private Connection conn;
    private String driver,oracle;
    private String matricola,codicefiscale,nome,cognome;
	
	
    public insert_dipendente() {
        super();
    }
    
    public void init(ServletConfig sc) throws ServletException
    {
    	super.init(sc);
		driver = "oracle.jdbc.driver.OracleDriver";
		oracle = "jdbc:oracle:thin:@localhost:1521:xe";
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String qry="";
	
		matricola = request.getParameter("matricola");
		codicefiscale  = request.getParameter("codicefiscale");
		nome  = request.getParameter("nome");
		cognome  = request.getParameter("cognome");
		
		try {
			conn = DriverManager.getConnection(oracle, oracleUser, oraclePwd);
			conn.setAutoCommit(false);
			Statement st = conn.createStatement();
			System.out.println("Matricola:"+matricola+" lunghezza:"+matricola.length());
			if (matricola.length()==0)
				qry = "insert into personale (codicefiscale,nome,cognome) "
				       + "values('"+codicefiscale+"','"+nome+"','"+cognome+"')";
			else
				qry = "insert into personale (matricola,codicefiscale,nome,cognome) "
				       + "values("+matricola+",'"+codicefiscale+"','"+nome+"','"+cognome+"')";
			System.out.println(qry);
			ResultSet rs = st.executeQuery(qry);
			if(matricola.length()==0)
				qry="select matricola from personale where codicefiscale='"+codicefiscale+"'";
			rs=st.executeQuery(qry);
			rs.next();
			matricola=rs.getString("matricola");
			System.out.println(matricola);
			rs.close();
			conn.commit();
			st.close();
			conn.close();
			
			response.sendRedirect("adm/dip/nuovo_account.jsp?matricola="+matricola);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

}
